package org.common.utils.fasttest;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.LockSupport;

/**
 * @author zhouzhibing
 * @date 2024/11/21
 */
public class TestLockSupport {

    public static void test() throws Exception {

//        test1();
        test2();
//        test3();
//        test4();
    }


    public static void test1() throws InterruptedException {
        //park不限时
        Thread thread = new Thread(() -> LockSupport.park());
        //park限时
        Thread thread2 = new Thread(() -> LockSupport.parkNanos(3000000000l));
        thread.start();
        thread2.start();
        //主线睡眠一秒,让子线程充分运行
        Thread.sleep(1000);
        //获取处于park的子线程状态
        System.out.println(thread.getState());
        System.out.println(thread2.getState());
    }

    /**
     * park/unpark测试
     */
    public static void test2() {
        System.out.println("begin park");
//        String name = "张三";
//        LockSupport.park(name);
//        Object blocker = LockSupport.getBlocker(Thread.currentThread());

        //调用park方法
        LockSupport.park();
        //使当前线程获取到许可证,明显执行不到这一步来,因为在上一步就已经阻塞了
        LockSupport.unpark(Thread.currentThread());
        System.out.println("end park");
    }

    /**
     * park/unpark测试
     */
    public static void test3() {
        System.out.println("begin park");
        //使当前线程先获取到许可证
        LockSupport.unpark(Thread.currentThread());
        //再次调用park方法,先获得了许可,因此该方法不会阻塞
        LockSupport.park();
        System.out.println("end park");
    }

    /**
     * park/unpark测试
     */
    public static void test4() throws Exception {
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                long currentTimeMillis = System.currentTimeMillis();
                System.out.println("begin park");
                LockSupport.park();
                System.out.println("end park");
                System.out.println(System.currentTimeMillis() - currentTimeMillis);
            }
        });
        thread.start();
        //开放或者注释该行代码,观察end park时间
//        Thread.sleep(2000);
        //使当子线程获取到许可证
        LockSupport.unpark(thread);
    }

}
